import React, { Component } from 'react';
import { Input, Button, Checkbox, Select } from 'antd';
import { createForm } from 'rc-form';
import Relay from 'react-relay';

class myForm extends Component {
  onSubmit = () => {
    const { form, mutation, data } = this.props;
    const mutationData = this.props.mutationData || {};
    form.validateFields((error, value) => {
      if (error){

      } else {
        mutationData.payload = Object.assign({},mutationData.payload, value);
        console.log(mutationData)
        Relay.Store.commitUpdate(
          new mutation(mutationData), {
            onSuccess: () => {
              this.props.onSubmit()
            },
            onFailure: () => {
              alert('出错了，请检查网络，请稍后再试')
            },
          },
        );
      }
    });
  };
  onCancel = () => {
    this.props.onCancel()
  };

  render() {
    const { fields, form, data, checkFields, selectFields } = this.props;
    const { getFieldProps, getFieldError } = form;
    return (
      <div>
        {
          checkFields ?
            checkFields.map(cf => (
              <Checkbox
                checked={cf.init ? cf.init : false}
                {...getFieldProps(cf.name, {})}
              >{cf.label}</Checkbox>
            ))
            : null
        }

        {
          selectFields ?
            selectFields.map(sf => (
              <div>
                <span>{sf.label}</span>
                <Select defaultValue={sf.default} style={{width: 400}}
                  {...getFieldProps(sf.name, {})}
                >
                  {
                    sf.choices.map(choice => (
                      <Select.Option value={choice.value === undefined ? choice : choice.value}>{choice.name || choice} </Select.Option>
                    ))
                  }
                </Select>
                <div style={{ margin: '24px 0' }} />
              </div>
            )) : null
        }
        {
          fields ?
          fields.map(field => (<div>
              <Input
                placeholder={field.placeholder}
                {...getFieldProps(field.name, {
                  initialValue: data ? data[field.name] : null,
                  rules: [{ required: true }],
                })}
              />
              <div style={{ margin: '24px 0' }} />
            </div>
          )) :  null
        }
        <Button type="primary" onClick={this.onSubmit}>确定</Button>
        <Button onClick={this.onCancel}>取消</Button>
      </div>
    )
  }
};

export default createForm()(myForm);
